import java.util.LinkedList;
import java.util.Queue;

public class Solution778 {

    int[] dx={0,1,0,-1};
    int[] dy={1,0,-1,0};

    public int swimInWater(int[][] grid) {
        int n=grid.length;
        int l=Math.max(grid[0][0],grid[n-1][n-1]),r=n*n;
        int ans=-1;
        while (l<=r){
            int mid=(l+r)/2;
            if (check(mid,grid)){
                ans=mid;
                r=mid-1;
            }else{
                l=mid+1;
            }
        }
        return ans;
    }

    private boolean check(int t,int[][] grid) {
        Queue<int[]> queue=new LinkedList<>();
        int[][] visit=new int[grid.length][grid.length];
        visit[0][0]=1;
        queue.offer(new int[]{0,0});
        while (!queue.isEmpty()){
            int[] p=queue.poll();
            for (int i = 0; i < 4; i++) {
                int x=p[0]+dx[i];
                int y=p[1]+dy[i];
                if (valid(x,y,grid.length) && visit[x][y]==0 && grid[x][y]<=t){
                    queue.offer(new int[]{x,y});
                    visit[x][y]=1;
                }
            }
        }
        return visit[grid.length-1][grid.length-1]==1;
    }

    private boolean valid(int x, int y, int length) {
        return x>=0 && x<length && y>=0 && y<length;
    }

    public static void main(String[] args) {
        System.out.println(new Solution778().swimInWater(new int[][]{{0,1,2,3,4},{24,23,22,21,5},{12,13,14,15,16},{11,17,18,19,20},{10,9,8,7,6}}));
    }
}
